package com.xtayfjpk.security.digest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;

import org.junit.Test;

import com.xtayfjpk.security.utils.SecurityUtils;

public class DigestTest {
	
	@Test
	public void testDigestInputStream() throws Exception {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		String value = "xtayfjpk";
		byte[] bytes = value.getBytes();
		DigestInputStream stream = new DigestInputStream(new ByteArrayInputStream(bytes), digest);
		//一定要开启，默认为开启
		stream.on(true);
		stream.read(bytes);
		byte[] result = stream.getMessageDigest().digest();
		System.out.println(SecurityUtils.toHexString(result));
		System.out.println(new String(bytes));
		stream.close();
	}
	
	@Test
	public void testDigestOutStream() throws Exception {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		String value = "xtayfjpk";
		byte[] bytes = value.getBytes();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DigestOutputStream stream = new DigestOutputStream(baos, digest);
		//一定要开启，默认为开启
		stream.on(true);
		stream.write(bytes);
		byte[] result = stream.getMessageDigest().digest();
		System.out.println(SecurityUtils.toHexString(result));
		System.out.println(new String(baos.toByteArray()));
		stream.close();
	}
	
	@Test
	public void testMac() throws Exception {
		String myInfo = "我的测试信息";
		Mac digest = Mac.getInstance("HmacSHA512");
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		digest.init(keyGenerator.generateKey());
		//必须用密钥进行初始化，而MessageDigest不需要
		digest.update(myInfo.getBytes());
		byte[] result = digest.doFinal();
		System.out.println("本信息摘要为：" + SecurityUtils.toHexString(result));
		
	}
}
